from flask import Flask
import akshare as ak
import datetime
import pandas as pd
import json
from flask_cors import CORS
# 导入user模块
from handler.user import user
from handler.stockInfo import stockInfo
from handler.strategy import strategy
from handler.recommand import recommand
# app = Flask(__name__)
from db_config import app
app.secret_key='13579'
CORS(app,support_credentials=True)
#用户模块  user/login   user/register  user/changepwd
app.register_blueprint(user,url_prefix="/user")

#股票信息模块
app.register_blueprint(stockInfo,url_prefix="/stockInfo")

#策略模块
app.register_blueprint(strategy,url_prefix="/strategy")

#推荐股票模块
app.register_blueprint(recommand,url_prefix="/recommand")



@app.route('/')
def get_homeData():

    home_dic={}

    # 上证指数 深证指数 沪深300
    SZ_SZ_HSdata=get_SZ_SZ_HS_data()
    home_dic["shenzheng"]=SZ_SZ_HSdata[0]
    home_dic["shangzheng"]=SZ_SZ_HSdata[1]
    home_dic["hushen"]=SZ_SZ_HSdata[2]
    
    # 大盘信息
    dapanData_jinge,dapan_jingzhanbi=get_dapan()
    home_dic["jinge"] = dapanData_jinge
    home_dic["jingzhanbi"] = dapan_jingzhanbi


    #板块信息
    bankuaiData_companyNum,bankuaiData_dealNum,bankuaiData_dealPrice= get_bankuai()
    bankuaiData_rank = get_bankuaiRank()
    home_dic["bankuai_company"]=bankuaiData_companyNum
    home_dic["bankuai_chengjiaoliang"]=bankuaiData_dealNum
    home_dic["bankuai_chengjiaoe"]=bankuaiData_dealPrice
    home_dic["bankuaiRank"] = bankuaiData_rank

    ##排名信息
    rank_companyData = get_500Company()
    rank_geguData = geGu_rank()
    home_dic["company500"] = rank_companyData
    home_dic["geguRank"] = rank_geguData

    #json格式化
    home_dic = json.dumps(home_dic, ensure_ascii=False)
    return home_dic







# =============================================================深证成指\上证指数\沪深300 数据获取===================================================================
def get_SZ_SZ_HS_data():
    today = datetime.date.today()
    start_data=['1991-04-03','1990-12-19','2002-01-04']
    data_total=[]
    for start_data_index in range(3):
        data_index = pd.date_range(start_data[start_data_index], today)  # DataFrame 第一列时间获取不到
        data_list = [pd.Timestamp(x).strftime("%Y-%m-%d") for x in data_index.values]
        data_total.append(data_list)



    data_code=["sz399001","sh000001","sh000300"]
    # data_index=["深证成指","上证指数","沪深300"]
    res=[]

    for codeStrIndex in range(3):

        SZ_SZ_HS_data = ak.stock_zh_index_daily(symbol=data_code[codeStrIndex])  # sh.000300 沪深300，sz.399001 深证成指 上证指数 sh000001
        # print(SZ_SZ_HS_data)
        dataUse_list=data_total[codeStrIndex][-100:]
        open_list = list(SZ_SZ_HS_data["open"])[-100:]
        close_list = list(SZ_SZ_HS_data["close"])[-100:]
        low_list = list(SZ_SZ_HS_data["low"])[-100:]
        high_list = list(SZ_SZ_HS_data["high"])[-100:]
        SZ_SZ_HS_data_len = len(open_list)

        SZ_SZ_HS_list = [] #字典对应的value值
        for index in range(SZ_SZ_HS_data_len):
            line_list = [] #每一行数据
            line_list.append(dataUse_list[index])
            line_list.append(float(open_list[index]))
            line_list.append(float(close_list[index]))
            line_list.append(float(low_list[index]))
            line_list.append(float(high_list[index]))
            SZ_SZ_HS_list.append(line_list)

        res.append(SZ_SZ_HS_list)#选取近一年数据，否则数据量太大
    return res


# ================================获取大盘数据================================
def get_dapan():
    dapan_data = ak.stock_market_fund_flow()

    data_list=list(dapan_data["日期"])
    name_list = ["主力","超大单","大单","中单","小单"]
    zhuliJinge_list = list(dapan_data["主力净流入-净额"])
    chaodadanJjinge_list = list(dapan_data["超大单净流入-净额"])
    dadanJinge_list = list(dapan_data["大单净流入-净额"])
    zhongdanJinge_list = list(dapan_data["中单净流入-净额"])
    xiaodanJinge_list = list(dapan_data["小单净流入-净额"])

    jinge_list=[]
    jinge_list.append(data_list)
    jinge_list.append(name_list)
    jinge_list.append(zhuliJinge_list)
    jinge_list.append(chaodadanJjinge_list)
    jinge_list.append(dadanJinge_list)
    jinge_list.append(zhongdanJinge_list)
    jinge_list.append(xiaodanJinge_list)

    # jinge_dic = {}
    # jinge_dic["jinge"] = jinge_list
    # jinge_dic = json.dumps(jinge_dic, ensure_ascii=False)


    #=================净占比==================
    zhuliJingzhanbi_list = list(dapan_data["主力净流入-净占比"])
    chaodadanJjingzhanbi_list = list(dapan_data["超大单净流入-净占比"])
    dadanJingzhanbi_list = list(dapan_data["大单净流入-净占比"])
    zhongdanJingzhanbi_list = list(dapan_data["中单净流入-净占比"])
    xiaodanJingzhanbi_list = list(dapan_data["小单净流入-净占比"])

    jingzhanbi_list = []
    jingzhanbi_list.append(data_list)
    jingzhanbi_list.append(name_list)
    jingzhanbi_list.append(zhuliJingzhanbi_list)
    jingzhanbi_list.append(chaodadanJjingzhanbi_list)
    jingzhanbi_list.append(dadanJingzhanbi_list)
    jingzhanbi_list.append(zhongdanJingzhanbi_list)
    jingzhanbi_list.append(xiaodanJingzhanbi_list)

    return jinge_list,jingzhanbi_list

    # jingzhanbi_dic = {}
    # jingzhanbi_dic["jingzhanbi"] = jingzhanbi_list
    # jingzhanbi_dic = json.dumps(jingzhanbi_dic, ensure_ascii=False)
    # print(jingzhanbi_dic)



# ==================================================================板块数据获取============================================================================

def get_bankuai():
    stockBanKuai = ak.stock_sector_spot()

    # 需要的数据
    bankuai = list(stockBanKuai["板块"])
    companyNum = list(stockBanKuai["公司家数"])
    dealNum = list(stockBanKuai["总成交量(手)"])
    dealPrice = list(stockBanKuai["总成交额(万元)"])

    bankuai_companyNum = []
    bankuai_dealNum = []
    bankuai_dealPrice = []

    for bankuai_index in range(len(bankuai)):
        line_dic1={}
        line_dic2={}
        line_dic3 = {}
        line_dic1["value"]=int(companyNum[bankuai_index])
        line_dic1["name"] = bankuai[bankuai_index]
        bankuai_companyNum.append(line_dic1)

        line_dic2["value"]=int(dealNum[bankuai_index])
        line_dic2["name"] = bankuai[bankuai_index]
        bankuai_dealNum.append(line_dic2)

        line_dic3["value"] = int(dealPrice[bankuai_index])
        line_dic3["name"] = bankuai[bankuai_index]
        bankuai_dealPrice.append(line_dic3)

    # print(bankuai_companyNum)
    # print(bankuai_dealNum)
    # print(bankuai_dealPrice)
    return bankuai_companyNum, bankuai_dealNum,bankuai_dealPrice
    # print(result_dic["板块公司家数"])

def get_bankuaiRank():
    # # #板块资金流排名
    # 板块名称 板块代码 涨跌幅 主力净流入-净额 主力净流入-净占比 主力净流入最大股
    bankuaiMoney_data = ak.stock_sector_fund_flow_rank("5日")

    #print(list(bankuaiMoney_data))
    # print(list(bankuaiMoney_data))
    zhangDieFu_list = list(bankuaiMoney_data["涨跌幅"])
    code_list = list(bankuaiMoney_data["板块代码"])
    name_list = list(bankuaiMoney_data["板块名称"])
    jingE_list = list(bankuaiMoney_data["主力净流入-净额"])
    jingZhanBi_list = list(bankuaiMoney_data["主力净流入-净占比"])
    zuiDaGu_list = list(bankuaiMoney_data["主力净流入最大股"])

    bankuai_dic = []
    for index in range(len(name_list)):
        line_dic={}
        line_dic["name"] = name_list[index]
        line_dic["code"] = code_list[index]
        line_dic["zhangdiefu"] = zhangDieFu_list[index]
        line_dic["jinge"] =jingE_list[index]
        line_dic["jingzhanbi"] = jingZhanBi_list[index]
        line_dic["zuidagu"] = zuiDaGu_list[index]

        bankuai_dic.append(line_dic)
    
    return bankuai_dic

# =================================排行数据获取===========================================
def get_500Company():
    # 公司名称（中英） 营业收入 百万美元 利润百万美元 国家
    company500 = ak.fortune_rank("2019")#最新是2019
    # print(company500)
    # tilename=list(company500)
    company500_length = len(company500)
    company500_tableData = []
    for index in range(company500_length):
        linedata = {}
        linedata["num"]=index
        for valueindex in range(4):
            linedata["name"]=company500.iloc[index][0]
            linedata["incoming"] = company500.iloc[index][1]
            linedata["profit"] = company500.iloc[index][2]
            linedata["country"] = company500.iloc[index][3]
        company500_tableData.append(linedata)
    
    return company500_tableData[:100] #控制数据量

def geGu_rank():
    # #个股资金流
    # 代码 名称 最新价 涨跌幅
    print("------------------")
    geGu_data = ak.stock_individual_fund_flow_rank()
    print("------------------")
    print(list(geGu_data))
    print("------------------")
    name_list = list(geGu_data["名称"])
    code_list = list(geGu_data["代码"])
    zhangDieFu_list = list(geGu_data["涨跌幅"])
    newPrice_list = list(geGu_data["最新价"])

    gegu_dic=[] #要返回的结果
    for index in range(len(name_list)):
        line_dic={}
        line_dic["name"]= name_list[index]
        line_dic["code"] = code_list[index]
        line_dic["zhangdiefu"]= zhangDieFu_list[index]
        line_dic["newprice"] = newPrice_list[index]
        gegu_dic.append(line_dic)
    
    return gegu_dic[:100]


if __name__=='__main__':
    app.run(host="0.0.0.0",port="5000",debug=True)
    # app.run(host="127.0.0.1",port="5000",debug=True)
